<?php

namespace App\Models\User;

use App\Models\Article\ArticleOrder;
use App\Models\Common\CommonModel;
use App\Models\Constant\Constant;
use App\Models\Setting\SysSetting;
use EasyWeChat\Factory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;

class User extends CommonModel
{
    use HasFactory,SoftDeletes;
    protected $table = 'user';
    protected $hidden = ['pwd_content','password','deleted_at'];


    public function getUserLastOrder($auto=1) {
        return MemberOrder::query()->where(['user_id'=>$this->id,'is_finished'=>1,'is_auto'=>$auto])->first();
    }

    /**
     * @deprecated
     * @return mixed
     */
    public function getMemberType() {
        return MemberOrder::where(['user_id'=>$this->id,'is_finished'=>1])->orderBy('id','desc')->get()->first();
    }

    public function addSeeLog($articleId,$type=Constant::SEE_LOG_TYPE_SEE) {
        return SeeLog::query()->updateOrCreate(['user_id'=>$this->id,'article_id'=>$articleId],[
            'user_id'=>$this->id,
            'article_id'=>$articleId,
            'type'=>$type,
            'day'=>date('Y-m-d')
        ]);
    }


    public function isBuyFirst():bool {
        return MemberOrder::where(['user_id'=>$this->id,'is_finished'=>1,'type'=>'first'])->exists();
    }
    public function isExBuyFirst():bool {
        return MemberOrder::where(['user_id'=>$this->id,'is_finished'=>1,'type'=>'exfirst'])->count()>=Constant::ExFirst;
    }

    public function isMoreThanDownloadForPPT() :bool {
        return $this->download_ppt <= $this->getCurrentDownload('pptx');

    }

    public function isMoreThanDownloadForDocx() :bool {
        return $this->download_word <= $this->getCurrentDownload('docx');

    }

    protected function getCurrentDownload(string $type) :int {
        return UserDownloadLog::where('user_id',$this->id)->where('article_type',$type)->count();
    }

    public function isBuyArticle(int $articleId) :bool {
        return ArticleOrder::where('user_id',$this->id)->where('article_id',$articleId)->where('is_finished',1)->exists();
    }

    public function getDownloadWord(){
        return $this->hasMany(UserDownloadLog::class,'user_id','id')->where('article_type','docx');
    }

    public function getDownloadPpt(){
        return $this->hasMany(UserDownloadLog::class,'user_id','id')->where('article_type','pptx');
    }

    public function giveParentUserToHongBao($type,$wishText='感谢您对的支持'){

        if($this->parent_id==0){
            return [
                'flag'=>false,
                'msg'=>'父id等于0'
            ];
        }
        $parentUser = $this->where('id',$this->parent_id)->first();
        if(empty($parentUser))
            return [
                'flag'=>false,
                'msg'=>'未查找到父用户！'
            ];

        if(empty($parentUser->open_id))
            return [
                'flag'=>false,
                'msg'=>'父用户缺少openId！'
            ];

        //如果已经返现过红包，就不再次返现了
        if(CallbackMoneyLog::isCallbackMoney($this->id, $this->parent_id)){
            return [
                'flag'=>false,
                'msg'=>'已经返过现了'
            ];
        }

        $moneyMap = [
            'first'=>150,
            'month'=>300,
            'quarter'=>800,
            'year'=>2000,
        ];

        $config = config('wechat.default');
        $payment = Factory::payment($config);
        $redpack = $payment->redpack;
        $redpackData = [
            'mch_billno'   => uniqid().time(),
            'send_name'    => '会员返现',
            're_openid'    => $parentUser->open_id,
            'total_num'    => 1,  //固定为1，可不传
            'total_amount' => $moneyMap[$type]??150,  //单位为分，不小于100
            'wishing'      => $wishText,
            'act_name'     => '会员返现',
            'remark'       => '会员返现',

        ];
        $res = $redpack->sendNormal($redpackData);

        //记录返现log
        CallbackMoneyLog::create(['buy_user_id'=>$this->id,'parent_id'=>$this->parent_id,'fee'=>$redpackData['total_amount']]);

        return [
            'flag'=>true,
            'msg'=>$res
        ];
    }


}
